package com.gdc.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * Description: 流量限制演示 Controller
 * @author: gdc
 * @date: 2021/2/8
 * @version 1.0
 */
@Slf4j
@RestController
public class FlowLimitController {

    @GetMapping("/testA")
    public String testA() {
        return "----testA";
    }

    @GetMapping("/testB")
    public String testB() {
        return "----testB";
    }

    @GetMapping("/testC")
    public String testC() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        log.info("testC 测试 【RT】");
        return "----testC";
    }

    @GetMapping("/testD")
    public String testD() {
        log.info("testD 测试 【异常比例】");

        int num = 10 / 0;
        return "----testD";
    }

    @GetMapping("/testE")
    public String testE() {
        log.info("testD 测试 【异常数】");

        int num = 10 / 0;
        return "----testE";
    }

    /**
     * 测试热点Key功能
     *
     *  - @SentinelResource
     *      - value: 资源名称，不能为空，需要保证唯一，填写在管理平台_热点规则_资源名
     *      - blockHandler：指定具体的处理函数，不设置时，当不满足规则时，会返回异常数据页面
     */
    @GetMapping("/testHotKey")
    @SentinelResource(value = "testHotKey", blockHandler = "deal_testHotKey")
    public String testHotKey(@RequestParam(value = "p1", required = false) String p1,
                             @RequestParam(value = "p2", required = false) String p2) {
        return "----testHotKey";
    }

    /**
     * 违背热点规则的兜底解决方案
     */
    public String deal_testHotKey(String p1, String p2, BlockException exception) {
        // sentinel 系统默认的提示：Blocked by Sentinel (flow limiting)
        return "----deal_testHotKey,o(╥﹏╥)o";
    }

}